package moco.blatt8.zeitabfrageasync;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
	
	private Context context = this;
	private TextView tv;
	private ProgressDialog pd;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		tv =(TextView) findViewById(R.id.tv);
		
		Button btn = (Button) findViewById(R.id.button1);
		btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				_startAsyncTask();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	
	private void _startAsyncTask(){
		new AsyncTask<String, String, String>() {

			@Override
			protected void onPreExecute() {
				pd = new ProgressDialog(context);
				pd.setMessage("Warten...");
				pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				pd.show();
				super.onPreExecute();
			}
			
			@Override
			protected String doInBackground(String... params) {
				String res = null;
				
				try {
					Thread.sleep(2000);
					Socket socket = new Socket(SocketUtils.HOST,SocketUtils.PORT);
					
					BufferedReader br = SocketUtils.getReader(socket);
					br.readLine();
					res = br.readLine();
					socket.close();
				} catch (UnknownHostException e) {
					_terminate(e);
				} catch (IOException e) {
					_terminate(e);
				}catch (InterruptedException e) {
					_terminate(e);
				}
				
				return res;
			}
			
			@Override
			protected void onPostExecute(String result) {
				pd.cancel();
				tv.setText(result);
				super.onPostExecute(result);
			}
			
		}.execute("");
	}
	
	private void _terminate(Exception ex){
		String text = "Fehler: ";
		if(pd != null)
			pd.cancel();
		if(ex != null) {
			text = ex.getMessage();
		}
		System.out.println(text);
	}

}
